package com.tongtech.system.service.impl;

import com.tongtech.common.security.utils.SecurityUtils;
import com.tongtech.system.api.domain.SysUser;
import com.tongtech.system.api.model.LoginUser;
import com.tongtech.system.domain.Customer;
import com.tongtech.system.enums.UserType;
import com.tongtech.system.mapper.CustomerMapper;
import com.tongtech.system.service.ICustomerService;
import com.tongtech.system.service.ISysUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.constraints.Email;
import javax.validation.constraints.Size;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 客户管理 服务实现
 *
 * @author xingyc
 */
@Service
public class CustomerServiceImpl implements ICustomerService
{
    @Autowired
    private CustomerMapper customerMapper;

    @Autowired
    private ISysUserService userService;

    /**
     * 查询客户管理数据
     *
     * @param customer 客户信息
     * @return 客户信息集合
     */
    @Override
    public List<Customer> selectCustomerList(Customer customer)
    {
        List<Customer> list = customerMapper.selectCustomerList(customer);

        return list;
    }

    /**
     * 根据客户ID查询信息
     *
     * @param customerId 客户ID
     * @return 客户信息
     */
    @Override
    public Customer selectCustomerById(Long customerId)
    {
        Customer customer = customerMapper.selectCustomerById(customerId);
        if (Objects.nonNull(customer)){
            Long marketerId = customer.getMarketerId();
            if(Objects.nonNull(marketerId)){
                SysUser sysUser = userService.selectUserById(marketerId);
                if(Objects.nonNull(sysUser)){
                    String nickName = sysUser.getNickName();
                    customer.setMarketerName(nickName);
                }
            }

            Long projectManagerId = customer.getProjectManagerId();
            if(Objects.nonNull(projectManagerId)){
                SysUser sysUser = userService.selectUserById(projectManagerId);
                if(Objects.nonNull(sysUser)){
                    String nickName = sysUser.getNickName();
                    customer.setProjectManagerName(nickName);
                }
            }
        }
        return customer;
    }

    /**
     * 根据客户邮箱查询信息
     *
     * @param email 客户邮箱
     * @return 客户信息
     */
    @Override
    public Customer selectCustomerByEmail(String email)
    {
        Customer customer = customerMapper.selectCustomerByEmail(email);
        return customer;
    }

    /**
     * 查询C端用户，当前的大客户经理信息
     */
    @Override
    public Map<String, String> selectProjectInfo() {
        Map<String, String> map = new ConcurrentHashMap<>();
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if(Objects.nonNull(loginUser)){
            //跟客户信息里的邮箱对应
            String userName = loginUser.getUsername();
            if(StringUtils.isNotEmpty(userName)){
                Customer customer = selectCustomerByEmail(userName);
                if(Objects.nonNull(customer)){
                    Long projectManagerId = customer.getProjectManagerId();
                    if(Objects.nonNull(projectManagerId)){
                        SysUser sysUser = userService.selectUserById(projectManagerId);
                        if(Objects.nonNull(sysUser)){
                            String nickName = sysUser.getNickName();
                            String email = sysUser.getEmail();
                            String phone = sysUser.getPhonenumber();
                            map.put("projectManagerName", nickName);
                            map.put("projectManagerEmail", email);
                            map.put("projectManagerPhone", phone);
                        }
                    }
                }
            }
        }
        return map;
    }

    /**
     * 新增保存客户信息
     *
     * @param customer 客户信息
     * @return 结果
     */
    @Override
    @Transactional
    public int insertCustomer(Customer customer)
    {
        // 录入客户信息
        int result = customerMapper.insertCustomer(customer);
        // 自动录入用户体系，并设置用户类型为大客户。若有邮箱则密码为邮箱+英文逗号，否则密码默认为Tc11@#,!
        String customerEmial = customer.getEmail();
        SysUser user = new SysUser();
        //内置的部门和角色
        user.setDeptId(111L);
        user.setRoleIds(new Long[]{5L});
        user.setUserName(customerEmial);
        user.setNickName(customer.getName());
        user.setEmail(customerEmial);
        user.setPhonenumber(customer.getPhone());
        user.setSex(customer.getSex());
        user.setUserType(UserType.MAJOR_CLIENTS_USER.getCode());
        user.setPassword(SecurityUtils.encryptPassword(StringUtils.isNoneEmpty(customerEmial) ? customerEmial + "," : "Tc11@#,!"));
        userService.insertUser(user);
        return result;
    }

    /**
     * 修改保存客户信息
     *
     * @param customer 客户信息
     * @return 结果
     */
    @Override
    @Transactional
    public int updateCustomer(Customer customer)
    {
        SysUser sysUser = null;
        String email = customer.getEmail();
        if(StringUtils.isNotEmpty(email)){
            //若修改了邮箱，需要同步到用户表
            Long customerId = customer.getCustomerId();
            Customer dbCustomer = selectCustomerById(customerId);
            if(Objects.nonNull(dbCustomer)){
                String dbEmail = dbCustomer.getEmail();
                if(StringUtils.isNotEmpty(dbEmail)){
                    sysUser = userService.selectUserByUserName(dbEmail);
                }
            }
        }
        int result = customerMapper.updateCustomer(customer);
        if(result > 0){
            if(Objects.nonNull(sysUser)){
                SysUser updateUser = new SysUser();
                updateUser.setUserId(sysUser.getUserId());
                updateUser.setUserName(email);
                updateUser.setEmail(email);
                userService.updateUserNameAndEmail(updateUser);
            }
        }
        return result;
    }

    /**
     * 删除客户管理信息
     *
     * @param deptId 客户ID
     * @return 结果
     */
    @Override
    public int deleteCustomerById(Long deptId)
    {
        return customerMapper.deleteCustomerById(deptId);
    }
}
